package ch08.shizhang.shizhang01;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 茜茜
 * @date 2024-11-29 16:51
 */
public class LoggingInvocationHandler implements InvocationHandler {
    private final  Object target;

    public LoggingInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //获取实现类中的方法信息
        Method methodTarget=target.getClass().getMethod(method.getName());
        //判断方法上面是否有Log注解
        if(methodTarget.isAnnotationPresent(Log.class)){
            String methodName=method.getName();
            DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime=LocalDateTime.now();
            System.out.println("[LOG]Method " + methodName+"startTime at"+startTime.format(formatter));
            Object result=method.invoke(target, args);
            LocalDateTime endTime=LocalDateTime.now();
            long duration=java.time.Duration.between(startTime,endTime).toMillis();
            System.out.println("[LOG]Method " + methodName+"end at"+endTime.format(formatter));
            System.out.println("[LOG]Method " + methodName+"executed in"+duration+"ms");
            return result;
        }else {
            return method.invoke(target, args);
        }
    }
}
